const express = require("express");
const router = express.Router();
// 模糊查询
const Op = require("sequelize").Op;
// 参数校验
const { body, validationResult } = require("express-validator");

const userModel = require("../../models/user");

// 添加用户
router.post(
  "/createUser",
  [
    // 验证请求体中的字段
    body("name")
      .isLength({ min: 5 })
      .withMessage("name must be at least 5 characters long"),
    body("password")
      .isLength({ min: 5 })
      .withMessage("password must be at least 5 characters long"),
  ],
  async (req, res, next) => {
    // 处理验证结果
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      // 如果有验证错误，返回错误信息
      return res.status(400).json({ errors: errors.array() });
    }

    const { name = "2x", password = "123456" } = req.body;
    try {
      // 向数据库添加数据
      const result = await userModel.create({ name, password });
      if (result) {
        res.status(200).json({
          code: 0,
          msg: "success",
        });
      }
    } catch (err) {
      next(err);
    }
  }
);

// 查询所有用户列表
router.get("/queryUserList", async (req, res, next) => {
  try {
    const result = await userModel.findAll();
    if (result) {
      res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    }
  } catch (err) {
    next(err);
  }
});

// 通过id查询用户
router.get("/queryUserById", async (req, res, next) => {
  const { id } = req.query;
  try {
    const result = await userModel.findByPk(id); // 通过住建查询
    if (result) {
      res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    }
  } catch (err) {
    next(err);
  }
});

// 修改用户
router.put("/updateUser", async (req, res, next) => {
  const { id, name, password } = req.body;
  try {
    const result = await userModel.update(
      { name, password },
      {
        where: { id },
      }
    );
    if (result) {
      res.json({
        code: 0,
        msg: "success",
      });
    }
  } catch (err) {
    next(err);
  }
});

// 通过id删除用户
router.delete("/deleteUserById", async (req, res, next) => {
  const { id } = req.query;
  try {
    const result = await userModel.destroy({
      where: { id },
    });
    if (result) {
      res.json({
        code: 0,
        msg: "success",
      });
    }
  } catch (err) {
    next(err);
  }
});

// 模糊查询
router.get("/link", async (req, res, next) => {
  const { name } = req.query;
  try {
    const result = await userModel.findAll({
      where: {
        name: {
          [Op.like]: name + "%",
        },
      },
    });
    if (result) {
      res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } else {
      res.json({
        code: 0,
        msg: "error",
      });
    }
  } catch (err) {
    next(err);
  }
});

module.exports = router;
